<template>
  <div>
    <el-tabs v-model="tabsName">
      <el-tab-pane label="用例详情" :name="'用例详情'">
        <el-button
          type="primary"
          @click="addStep()"
          size="mini"
          style="margin-bottom: 10px"
        >新增http请求
        </el-button
        >
        <span>调试环境:</span>
        <el-select
          v-model="envValue"
          placeholder="请选择"
          style="width: 240px"
          size="mini"
        >
          <el-option
            v-for="item in envList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-button
          size="mini"
          type="primary"
          style="float: right"
          @click="getBack()"
        >返回
        </el-button
        >
        <el-table
          border
          :data="stepList.data"
          id="crTable"
          ref="cTable"
          size="mini"
        >
          <el-table-column
            prop="name"
            label="步骤名称"
            width="300"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="path"
            label="请求地址"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="method"
            label="请求方式"
            width="300"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑
              </el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button
          @click="save(newStepList)"
          type="primary"
          size="mini"
          style="margin-top: 10px"
        >保存
        </el-button
        >
        <el-button
          @click="debug()"
          type="primary"
          size="mini"
          style="margin-top: 10px"
        >运行
        </el-button
        >
        <add-step-to-case-page
          :dialogFormVisible.sync="dialogFormVisible"
          v-on:changeAddStepPage="cap()"
        ></add-step-to-case-page>
      </el-tab-pane>
      <el-tab-pane
        v-for="(item, index) in editableTabs"
        :key="index"
        :label="item.title"
        :name="item.name"
      >
        <el-row>
          <el-col :span="6" class="colTable">用例名称</el-col>
          <el-col :span="18" class="colTable">{{
            testResults.caseName
            }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="colTable">开始时间</el-col>
          <el-col :span="6" class="colTable">{{ time }}</el-col>
          <el-col :span="6" class="colTable">用时</el-col>
          <el-col :span="6" class="colTable"
          >{{ testResults.apiTestCaseResult.testRunTime }}ms
          </el-col
          >
        </el-row>
        <el-row>
          <el-col :span="6" class="colTable">用例总数</el-col>
          <el-col :span="6" class="colTable">用例成功数</el-col>
          <el-col :span="6" class="colTable">用例失败数</el-col>
          <el-col :span="6" class="colTable">用例成功率</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="colTable">{{
            testResults.apiTestCaseResult.countResults
            }}
          </el-col>
          <el-col :span="6" class="colTable">{{
            testResults.apiTestCaseResult.passResults
            }}
          </el-col>
          <el-col :span="6" class="colTable">{{
            testResults.apiTestCaseResult.failedResults
            }}
          </el-col>
          <el-col :span="6" class="colTable"
          >{{
            (testResults.apiTestCaseResult.passResults /
            testResults.apiTestCaseResult.countResults) *
            100
            }}%
          </el-col
          >
        </el-row>
        <el-divider content-position="left">测试步骤</el-divider>
        <el-table :data="testResults.apiRequestResults" border>
          <el-table-column prop="apiName" label="步骤名称" align="center">
          </el-table-column>
          <el-table-column prop="resultIsPass" label="状态" align="center">
            <template slot-scope="scope">
              <el-tag size="medium" v-if="scope.row.resultIsPass == true">
                成功
              </el-tag>
              <el-tag size="medium" v-else type="danger"> 失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="耗时" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.resultTime }}ms</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="openDetail(scope.$index, scope.row)"
              >查看详情
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <api-result-drawer
          :ApiResultDrawer.sync="apiResult"
          :drawer="drawer"
          v-on:changeDrawer="ct"
        ></api-result-drawer>
      </el-tab-pane>
      <el-tab-pane label="编辑用例" :name="'编辑用例'" v-show="false">
        <StepDetails
          v-show="StepDetailsShow"
          :StepDetails.sync="StepDetails"
          :envList.sync="envList"
          v-on:getBack="onBack"
        ></StepDetails>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import AddStepToCasePage from "./AddStepToCasePage.vue";
  import ApiResultDrawer from "@/views/apiPage/ApiResultDrawer.vue";
  import StepDetails from "../testCase/StepDetails";
  import Sortable from "sortablejs";

  export default {

    components: {AddStepToCasePage, ApiResultDrawer, StepDetails},
    watch:{
      projectId:function () {
        this.$router.push("/TestCase")
      }
    },
    computed: {
      projectId: function () {
        return this.$store.getters.getProjectId;
      },
    },
    data() {
      return {
        envValue: "",
        envList: [{}],
        updateStepList: {},
        stepList: "",
        dialogFormVisible: false,
        drawer: false,
        show: false,
        time: "",
        newStepList: [],
        tabsName: "用例详情",
        editableTabs: [],
        testResults: "",
        StepDetails: {},
        StepDetailsShow: false,
        apiResult: {
            method: "",
        },
        tabIndex: 0,
      };
    },
    created() {
      let id = this.$route.query.id;
      this.stepListApi({testCaseId: id});
      this.getEnvList();


    },
    mounted() {
      this.rowDrop();

    },
    methods: {
      rowDrop() {
        const tbody = document
          .getElementById("crTable")
          .querySelector(".el-table__body-wrapper tbody");
        const that = this;
        Sortable.create(tbody, {
          animation: 150,
          ghostClass: "blue-background-class",
          onEnd({newIndex, oldIndex}) {
            console.log(newIndex, oldIndex);
            that.newStepList = JSON.parse(JSON.stringify(that.stepList.data));
            // console.log(that.stepList.data);
            const targetRow = that.newStepList.splice(oldIndex, 1)[0];
            console.log(targetRow);
            that.newStepList.splice(newIndex, 0, targetRow);
            // console.log(that.$refs.cTable.tableData);
            console.log(that.newStepList);
          },
        });
      },
      getEnvList() {
        this.$env
          .list({projectId: this.$store.getters.getProjectId})
          .then((res) => {
            this.envList = res.data;
            if (null!=this.envList&&this.envList.length>0){
              this.envValue =this.envList[0].id;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      },
      addStep() {
        this.dialogFormVisible = true;
        console.log("addStep");
      },
      getBack() {
        this.$router.back();
      },
      onBack() {
        this.tabsName = '用例详情';
        this.stepListApi({testCaseId: this.$route.query.id});
      },
      stepListApi(p) {
        this.$testCaseStep
          .sList(p)
          .then((res) => {
            if (res.code == 200) {
              this.stepList = res;
              this.newStepList = res.data
              if (Object.values(this.newStepList).length > 0) {
                this.envValue = this.newStepList[0].envId
              }

            }
          })
          .catch((res) => {
            console.log(res);
          });

      },
      handleEdit(index, row) {
        this.tabsName = "编辑用例"
        this.StepDetailsShow = true
        this.getEnvList();
        this.StepDetails = row
        console.log(index, row);
      },
      handleDelete(index, value) {
        console.log(index, value);
        this.$testCaseStep.sDelete({id: value.id}).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.stepListApi({testCaseId: this.$route.query.id});
          }
        });
      },
      cap() {
        this.stepListApi({testCaseId: this.$route.query.id})
        this.dialogFormVisible = false;
      },
      save(p) {
        this.updateStepList.apiTestCaseStepReqs = this.newStepList;
        this.updateStepList.envId = this.envValue;
        console.log("测试：updateStepList")
        console.log(this.updateStepList)
        this.$testCaseStep
          .sUpdate(this.updateStepList)
          .then((res) => {
            if (res.code == 200) {
              this.$message({
                message: "保存成功",
                type: "success",
              });
            }
          })
          .catch((res) => {
            this.$message.error("保存失败");
          });
      },
      debug() {
        const param = {}
        if (this.envValue) {
          param.envId = this.envValue
        }
        param.testCaseId = this.$route.query.id
        this.$testCase
          .tRun(param)
          .then((res) => {
            this.testResults = res.data;
            this.openTabPane();
            this.time = this.$dateFomat.timestampToTime(
              this.testResults.apiTestCaseResult.createTime * 1000
            );
            this.$message({
              message: "运行成功",
              type: "success",
            });
          })
          .catch((res) => {
            this.$message.error(res.message);
          });
      },
      openTabPane() {
        // console.log(this.editableTabs.length)
        if (this.editableTabs.length == 0) {
          this.editableTabs.push({
            title: "用例结果",
            name: "用例结果",
            content: "New Tab content",
          });
        } else if (this.editableTabs.length >= 1) {
          if (this.editableTabs[0].title != "用例结果") {
            this.editableTabs.push({
              title: "用例结果",
              name: "用例结果",
              content: "New Tab content",
            });
          }
        }
        ;
        this.tabsName = "用例结果";
      },
      openDetail(index, data) {
        console.log("index", index);
        console.log("data", data);
        this.apiResult = data;
        console.log(data.method);
        this.drawer = true;
      },
      ct() {
        this.drawer = false;
      },
    },
  };
</script>
<style>
  .colTable {
    border: 1px solid rgba(190, 188, 188, 0.32);
    display: inline-block;
    line-height: 36px;
    font-size: 14px !important;
    text-align: center;
  }
</style>
